const express = require("express")
const router = express.Router()
const historicalDB = require("../../../db/historical")
const { join } = require("path")
const fs = require("fs")

// 权限鉴别
router.use((req, res, next) => {
  if (!req.session.userInfo.allowDelete) {
    return res.send({
      code: 16,
      mes: "您没有删除权限，请练习超级管理员进行添加"
    })
  }
  next()
})

//删除分享
router.post("/", async (req, res) => {
  try {
    let { _id } = req.body
    // 检测该分享是否存在
    let doc = await historicalDB.findById(_id)
    if (!doc) {
      return res.send({
        code: 17,
        mes: "该历史人物已被删除，请刷新后重试"
      })
    }
    // 修改数据库
    await shareDB.findByIdAndRemove(_id)
    // 删除服务器文件
    fs.rm(join(__dirname, "../../../static" + doc.md), { recursive: true }, err => {
      if (err) return
    })
    doc.cover.forEach(item => {
      fs.rm(join(__dirname, "../../../static" + item), { recursive: true }, err => {
        if (err) return
      })
    })
    res.send({
      code: 0,
      mes: "删除成功"
    })
  } catch (error) {
    res.send({
      code: 5,
      mes: "服务器异常，请稍后再试"
    })
  }
})


module.exports = router